package com.hz.framework.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.Session;

import com.hz.sessionFactory.HibernateSessionFactory;

public class JdbcUtil {
	private static final long serialVersionUID = 6547617570485599616L;

	private Connection conn = null;
	private Session session=null;


	// -----------------------------------------------------

	// 从连接池获得连接
	public Connection getConnection() {
		closeConnection();
		try {
			session=HibernateSessionFactory.getSession();
			conn=session.connection();
			conn.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	// -----------------------------------------------------------
	// 使用本类必须在需要关闭连接的地方对连接进行关闭
	public void closeConnection() {
		if (conn != null) {
			try {
				if(!conn.isClosed())
				conn.close();				
				conn = null;
			} catch (Exception e) {
			}
		}
		if (session != null) {
			try {
				if(session.isOpen())
				session.close();				
				session = null;
			} catch (Exception e) {
			}
		}
	}
	//关闭JDBC
	public void closeAll(Connection conn,Statement st,ResultSet rs){
		// TODO 传入connection实例 Statement实例 ResultSet实例进行关闭 Connection必须是从DBQuery获得的
		if(null!=rs){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		closeAll(conn,st);
	}
	
	public void closeAll(Connection conn,Statement st){
		// TODO 传入connection实例 ResultSet实例进行关闭 Connection必须是从DBQuery获得的
		if(null!=st){
			try {
				st.close();
			} catch (Exception e) {
			}
		}
		if(null!=conn){
			closeConnection();
		}
	}
	

}
